package org.jjche.sys.modules.fillrule.api;

import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import lombok.RequiredArgsConstructor;
import org.jjche.cache.lock.annotation.JLock;
import org.jjche.common.exception.util.AssertUtil;
import org.jjche.core.handler.IFillRuleHandler;
import org.jjche.sys.enums.SysErrorCodeEnum;
import org.jjche.sys.modules.fillrule.domain.SysFillRuleDO;
import org.jjche.sys.modules.fillrule.service.SysFillRuleService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 系统编码规则服务,对内
 * </p>
 *
 * @author miaoyj
 * @since 2024-03-25
 */
@Service
@RequiredArgsConstructor
public class SysFillRuleApiImpl implements SysFillRuleApi {

    private final SysFillRuleService fillRuleService;

    /**
     * <p>
     * 生成编码
     * </p>
     *
     * @param ruleCode 规则编码
     * @param formData 数据
     * @return /
     */
    @JLock(lockKey = "#ruleCode")
    public String executeRule(String ruleCode, Map<String, Object> formData) {
        AssertUtil.notBlank(ruleCode, SysErrorCodeEnum.FILL_RULE_CODE_NOT_FOUND_ERROR, ruleCode);
        try {
            // 根据 ruleCode 查询出实体
            SysFillRuleDO fillRuleDO = this.fillRuleService.getBaseMapper().getByCode(ruleCode);
            AssertUtil.notNull(fillRuleDO, SysErrorCodeEnum.FILL_RULE_CODE_NOT_FOUND_ERROR, ruleCode);
            // 获取必要的参数
            String ruleClass = fillRuleDO.getRuleClass();
            Map<String, Object> params = JSONUtil.parseObj(fillRuleDO.getParams());
            if (params == null) {
                params = new HashMap<>();
            }
            if (formData == null) {
                formData = new HashMap<>();
            }
            // 通过反射执行配置的类里的方法
            IFillRuleHandler ruleHandler = (IFillRuleHandler) Class.forName(ruleClass).newInstance();
            return ruleHandler.execute(params, formData);
        } catch (Exception e) {
            StaticLog.error(e);
            throw new RuntimeException();
        }
    }
}
